
//  Durable subscriber
//
#include <stdint.h>
#include <string.h>

#include <stdlib.h>
#include <stdio.h>

#include <stdbool.h>
#include <stdarg.h>

#include <unistd.h>
#include <getopt.h>
#include <pthread.h>
#include <time.h>
#include <math.h>

#include <assert.h>

#include <sys/types.h>
#include <sys/time.h>

#include <elf.h>
#include <signal.h>
#include <semaphore.h>

#include <errno.h>
#include <syslog.h>
#include <curl/curl.h>
#include <dirent.h>

#include <zmq.h>
#include <czmq.h>

#include "msg_dcp.h"


int  main(int argc,char **argv) {

    void *context = zmq_init (1);

    char ch;
    int i=0,xptr=0,next=0;
	
    unsigned int ptr,leng;

    unsigned long int digest=0L,linger;

    DCP_MESSAGE	dhead;

    char *hoststr;
    if(argc<2){
	fprintf(stderr,"%d must with sub host parameter as tcp://connect_host:port \n",argc);
	exit(0);}

    hoststr = (char *) calloc(256,sizeof(char));
    
    sprintf(hoststr,"%s",argv[1]);
    fprintf(stderr,"connect %s as pull\n",hoststr);
    //  Connect our subscriber socket
    void *subscriber = zmq_socket(context, ZMQ_SUB);
    
    zmq_setsockopt (subscriber, ZMQ_SUBSCRIBE, "", 0);

     linger=320;
    zmq_setsockopt(subscriber, ZMQ_LINGER, &linger, sizeof(unsigned long int));
        linger = 8196;
    zmq_setsockopt(subscriber, ZMQ_SNDHWM, &linger, sizeof(unsigned long int));
    zmq_setsockopt(subscriber, ZMQ_RCVHWM, &linger, sizeof(unsigned long int));
        linger = 1024;
    zmq_setsockopt(subscriber, ZMQ_BACKLOG, &linger, sizeof(unsigned long int));

    zmq_connect(subscriber, hoststr);
    ptr = 0;

    while (1) {
      
	char *decmsg;
	int declen,sptr;

       unsigned char string[256];
       unsigned char sname[16];
       uint64_t xlong=0xAAAA5555;
      
       declen = zmq_recv(subscriber,string,256,0);

      memset(sname,0x0,16); 
	memcpy(&dhead,string,sizeof(DCP_MESSAGE));   //version == 2
        printf("%d v[%u] wCode[0x%x] ",declen,i,dhead.wCode);
        printf("->wFlags[0x%x]\t", dhead.wFlags);
        printf("->dwSize[0x%x]\t", dhead.dwSize);
        printf("->dwId[0x%x]\t", dhead.dwId);
        printf("->dwNumVars[0x%x] ", dhead.dwNumVars);
	sptr = sizeof(DCP_MESSAGE);
	memcpy(&xlong,decmsg+sptr,sizeof(uint64_t));	
	printf("recv[ %llx ]",xlong);

	printf("\n");
        i++;
    }
    zmq_close (sync);
    zmq_close (subscriber);
    zmq_term (context);
    return 0;
}
